from django.core.management.base import BaseCommand
import pika
import json
from ability.eanxing import experiment_list_data_send
from decouple import config
from datetime import date, datetime

class Command(BaseCommand):
    help = 'consume_eax_rabbitmq'

    # 约定实训平台消费Key
    queue_name = 'SatpTechnicalCommandDirectQueue'
    virtual_host = '/'

    def handle(self, *args, **options):
        try:
            credentials = pika.PlainCredentials(config('EAX_MQ_USER'), config('EAX_MQ_PASS'))  # 两个参数：用户名和密码
            connection = pika.BlockingConnection(
                pika.ConnectionParameters(host=config("EAX_MQ_HOST"), port=int(config('EAX_MQ_PROT')),
                                          virtual_host=self.virtual_host, credentials=credentials)  # 四个参数：机器、端口、虚拟主机、认证信息
            )
            channel = connection.channel()
            channel.queue_declare(queue=self.queue_name)
            channel.basic_consume(queue=self.queue_name, on_message_callback=consume_callback, auto_ack=True)
            # 开始等待消息
            print('['+datetime.now().strftime('%Y-%m-%d %H:%M:%S') +' start:]'+'Waiting for messages. To exit press CTRL+C')
            channel.start_consuming()
        except Exception as e:
            print(e)
            return False

def consume_callback(ch, method, properties, body):
    print("["+datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"] Received Message %r" % body)
    try:
        data = json.loads(body)
        if data is None:
            return None
        if data['action'] == 'init' and data['module'] == 'command':
            experiment_list_data_send()
        else:
            return None
    except Exception as e:
        print(e)
        return None
